# coding: utf-8
# @Author: 莫小鱼
import os
import yaml
from AutoApiTest.configs.setting import FILE_PATH
from AutoApiTest.unit_tools.log_util import logs


def read_yaml(yaml_path):
    """
    读取yaml文件数据
    :param yaml_path:文件路径
    :return:
    """
    try:
        testcase_list = []
        with open(yaml_path, 'r', encoding='utf-8') as file:
            data = yaml.safe_load(file)
            # 处理一个yaml文件多条用例场景
            if len(data) <= 1:
                yaml_data = data[0]
                base_info = yaml_data.get('baseInfo')

                for ts in yaml_data.get('testCase'):
                    params = [base_info, ts]
                    testcase_list.append(params)
                return testcase_list
            else:
                return data
    except UnicodeDecodeError:
        logs.error(f"{yaml_path}文件的编码格式异常,试试utf-8解码")
    except yaml.YAMLError as e:
        logs.error(f"Error: 读取yaml文件失败，请检查格式-{yaml_path},{e}")
    except Exception as e:
        logs.error(f"读取{yaml_path}文件异常：原因：{e}")


def write_yaml(value):
    """
    将获取到的value写入yaml文件，必须是字典类型
    :param value: (dict)
    :return:
    """
    file_path = FILE_PATH['extract']
    print(file_path)
    if not os.path.exists(file_path):
        with open(file_path, 'w', encoding='utf-8'):
            pass
    file = None
    try:
        file = open(file_path, 'a', encoding='utf-8')
        if isinstance(value, dict):
            write_data = yaml.dump(value, allow_unicode=True, sort_keys=False)
            file.write(write_data)
        else:
            logs.error("写入的数据必须为字典类型！！！")
    except Exception as e:
        logs.error(f"写入的yaml数据异常：{e}")
    finally:
        file.close()


def clear_yaml():
    """
    清空extract.yaml文件数据
    :return:
    """
    with open(FILE_PATH['extract'], 'w') as f:
        f.truncate()


def get_extract_yaml(node_name, sub_node_name=None):
    """
    用于获取extract.yaml文件的数据
    :param node_name: 第一级key值
    :param sub_node_name: 下一级key值
    :return:
    """
    file_path = FILE_PATH['extract']
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            extract_data = yaml.safe_load(file)
            if sub_node_name is None:
                return extract_data[node_name]
            else:
                return extract_data.get(node_name, {}).get(sub_node_name)
    except yaml.YAMLError as e:
        logs.error(f"Error: 读取yaml文件失败，请检查格式 -{file_path},{e}")
    except Exception as e:
        logs.error(f"Error：未知异常 -{e}")


if __name__ == '__main__':
    res = read_yaml('../../testcase/userManager/adduser.yaml')
    print(res)
    # ret = write_yaml({'xiaowu': 'sfewfw'})
    # print(ret)
    # ros = get_extract_yaml('Cookie', 'access_token_cookie')
    # print(ros)

    # clear_yaml()
